package edu.neusoft.yuejian_09.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import edu.neusoft.yuejian_09.R;
import edu.neusoft.yuejian_09.bean.Show;
import edu.neusoft.yuejian_09.model.ShowModel;
import edu.neusoft.yuejian_09.model.UserModel;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddShowActivity extends Activity {

    private ImageView img_return;//返回按钮
    private EditText noteContent;
    private Button noteSubmit;//发布图片按钮

    //新加入的
    public String filePath=null;
    int user_id;

    private ImageView mImage;
    private ImageButton mAddImage;
    private Bitmap mBitmap;
    protected static final int CHOOSE_PICTURE=0;
    protected static final int TAKE_PICTURE=1;
    protected static Uri tempUri;
    private static final int CROP_SMALL_PICTURE=2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_add_show);
        initViews();
        initEvents();
        getUserId();

    }

    public void initViews(){
        img_return=(ImageView)findViewById(R.id.img_return);
        noteContent=(EditText)findViewById(R.id.add_note);
        noteSubmit=(Button) findViewById(R.id.insure);
        mImage=(ImageView)findViewById(R.id.iv_image);
        mAddImage=(ImageButton)findViewById(R.id.btn_add_image);

    }
    public void initEvents(){
        noteSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pcontent=noteContent.getText().toString();
                if (pcontent.equals("")){
                    Toast.makeText(AddShowActivity.this,"请输入发帖信息", Toast.LENGTH_SHORT).show();
                }else {
                    upLoadPpicFile(filePath);
                }
            }
        });

        img_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });
        mAddImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChoosePicDialog();
            }
        });


    }
    //获取个人用户信息
    public void getUserId(){
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        user_id = sharedPreferences.getInt("user_id", 0);
    }

    //显示修改图片的对话框
    protected void showChoosePicDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(AddShowActivity.this);
        builder.setTitle("添加图片");
        String[] items={"选择本地图片","拍照"};
        builder.setNegativeButton("取消",null);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case CHOOSE_PICTURE://选择本地照片
                        Intent openAlbumIntent=new Intent(
                                Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        startActivityForResult(openAlbumIntent,CHOOSE_PICTURE);
                        break;
                    case TAKE_PICTURE://拍照
                        Intent openCameraIntent=new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri=Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"temp_image.jpg"));
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,tempUri);
                        startActivityForResult(openCameraIntent,TAKE_PICTURE);
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==AddShowActivity.RESULT_OK){
            switch (requestCode){
                case TAKE_PICTURE:
                    cutImage(tempUri);//对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    cutImage(data.getData());
                    break;
                case CROP_SMALL_PICTURE:
                    if (data!=null){
                        setImageToView(data);
                    }
                    break;
            }
        }
    }
    //裁剪图片的方法
    protected void cutImage(Uri uri){
        if (uri==null){
            Log.i("alanjet","The uri is not exist");
        }
        tempUri=uri;
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);

        intent.putExtra("outputX",150);
        intent.putExtra("outputY",150);
        intent.putExtra("return-data",true);
        startActivityForResult(intent,CROP_SMALL_PICTURE);
    }
    /**
     * 保存裁剪之后的图片数据
     */
    protected void setImageToView(Intent data){
        Bundle extras=data.getExtras();
        if (extras!=null){
            mBitmap=extras.getParcelable("data");
            mImage.setImageBitmap(mBitmap);
            filePath=saveMyBitmap("1",mBitmap);
        }
    }
    //上传图片
    private void upLoadPpicFile(String filePath){
        String ptext=noteContent.getText().toString();
        File file=new File(filePath);
        RequestBody requestFile=RequestBody.create(MediaType.parse("multipart/form-data"),file);
        MultipartBody.Part body=MultipartBody.Part.createFormData("file",file.getName(),requestFile);

        ShowModel showModel=new ShowModel();
        Call<Show> call=showModel.insertShow(user_id,ptext,body);
        call.enqueue(new Callback<Show>() {
            @Override
            public void onResponse(Call<Show> call, Response<Show> response) {
                try{
                    Toast.makeText(AddShowActivity.this,"发布成功",Toast.LENGTH_SHORT).show();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<Show> call, Throwable t) {

            }
        });
    }
    //获取bitmap
    public String saveMyBitmap(String bitName,Bitmap mBitmap){
        File f=new File("/sdcard/"+bitName+".jpg");
        String picPath="/sdcard/"+bitName+".jpg";
        try{
            f.createNewFile();
        }catch (IOException e){
            //DebugMessage.put("在保存图片时出错："+e.toString());
        }
        FileOutputStream fOut=null;
        try{
            fOut=new FileOutputStream(f);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG,100,fOut);
        try{
            fOut.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
        try{
            fOut.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return picPath;
    }

}
